const db = uniCloud.database();
const cmd = db.command;
const utils = require('quanzi-utils');
module.exports = {
    _before: async function() { // 通用预处理器
        this.userInfo = await utils.getUsetInfo(this);
        if (!this.userInfo.uid) throw this.userInfo;
    },
    async createOrder(data) {
        data.user_id = this.userInfo.uid;
        data.order_no = getOrderId();
        data.createTime = Date.now();
        //状态
        data.states = 0;
        data.done = false
        await db.collection('mall-order').add(data)
        return data.order_no;
    },
    //核对购买金额
    async getCountMoney(order_no, total_fee) {
        let user_order_success = true;
        //全部商品
        let orderRes = await db.collection('mall-order').where({
            order_no: order_no
        }).get();
        let cardList = orderRes.data[0].cardList;
        //订单编号
        let orderIdx = cardList.map(item => item._id);
        //订单内包含的商品
        let goodsRes = await db.collection('mall-goods').where({
            _id: cmd.in(orderIdx)
        }).get();
        //比较价格
        let sum = 0;
        goodsRes.data.map(item => {
            let index = cardList.findIndex(goods => goods._id == item._id);
            console.log(index);
            sum += cardList[index].shopNum * item.money
        })
        if (sum == total_fee) {
            db.collection('mall-order').where({
                order_no
            }).update({
                states: 1
            })

        } else {
            db.collection('mall-order').where({
                order_no
            }).update({
                states: -1
            })
            user_order_success = false;
        };
        return user_order_success;
    },
    //获取订单信息
    async getOrderList() {
        return await db.collection('mall-order').where({
            user_id: this.userInfo.uid,
            states: cmd.neq(0)
        }).get();
    },
    //获取单条订单信息
    async getOne(_id) {
        return await db.collection('mall-order').doc(_id).get();
    }
}

function getOrderId() {
    return Date.now() + "-" + String(Math.random()).substring(3, 9)
}